package com.sq.partner.manager.controller;

import java.io.File;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayPolicy;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayCustomerService;
import com.sq.partner.manager.service.IGatewayProductService;
import com.sq.partner.manager.service.IGatewayProtocolPolicyListService;
import com.sq.partner.manager.service.INlifeProdConfigService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
import com.sq.partner.manager.util.excel.ImportExcelBuilderTool;
import com.sq.partner.manager.util.excel.ImportExcelEntity;

@Controller
@RequestMapping(value = "/protocolPolicyList")
public class ProtocolPolicyListController {
	private static Logger logger = LogUtil.getLog(ProtocolPolicyListController.class);
	
	@Resource
	private IGatewayProtocolPolicyListService protocolPolicyListService;
	
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@Resource
	private IGatewayProductService productService;
	
	@Resource
	private IGatewayCustomerService customerService;
	
	@Resource
	private INlifeProdConfigService nlifeProdConfigService;
	
	@Resource
	ImportExcelBuilderTool importExcelBuilderTool;
	
	//跳转至查询页面
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(){
		return "transManager/protocolPolicyList";
	}
	
	
	/**
	 * 查询当前用户的权限机构
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryPrivilegeBranch",method = RequestMethod.POST)
	@ResponseBody
    public Result queryPrivilegeBranch(HttpSession session) throws Exception {
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
		
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			return Result.data(protocolPolicyListService.queryPrivilegeBranch(user.getDepartmentStr()));
		}
		
		return Result.fail();
		
		
    }
	
	/**
	 * 查询出单机构
	 * 
	 */
	@RequestMapping(value = "/queryDeptByDeptAndParentDeptCode",method = RequestMethod.POST)
	@ResponseBody
	public Page<CoreDept> queryDeptByDeptAndParentDeptCode(Integer size,Integer pageIndex,
				String deptCode,String deptCname,String parentDeptCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<CoreDept> page=new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		CoreDept dept=new CoreDept();
		dept.setDeptCode(deptCode);
		dept.setDeptCname(deptCname);
		page.setType(dept);

		return protocolPolicyListService.queryDeptPageByDeptAndParentDeptCode(page, parentDeptCode);
	}
	
	
	/**
	 * 查询合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryChannelInfoOfLife",method = RequestMethod.POST)
	public @ResponseBody Page<GatewayChannelInfo> queryChannelInfoOfLife(Integer size,Integer pageIndex,
									String parentDeptCode,String channelName,String channelCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(parentDeptCode);
		channelInfo.setChannelCode(channelCode);
		channelInfo.setChannelName(channelName);
		page.setType(channelInfo);
		return protocolPolicyListService.queryChannelInfoPageOfLife(page);
	}
	
	/**
	 * 分页条件查询车捷保保单
	 * 
	 */
	@RequestMapping(value = "/queryProtocolPolicyPageByCriteria")
	@ResponseBody
    public Page<Map<String,Object>> queryLifePolicyPageByCriteria(HttpSession session, Integer pageIndex,Integer size,
    			GatewayPolicy policy,String privilegeBranch,String bbrName,
    			String polBeginDateBegin,String polBeginDateEnd) throws Exception {
		
		Page page = beforeQueryProtocolPolicyPageByCriteria(session, pageIndex,size, policy, privilegeBranch,bbrName, polBeginDateBegin, polBeginDateEnd);
		if("error".equals(page.getResult()) || "noChannelInfo".equals(page.getResult())){
			return page;
		}
		return protocolPolicyListService.queryProtocolPolicyPageByCriteria(page);
    }
	
	/**
	 * 车捷保保单查询和保单信息下载前进行验证
	 */
	public Page beforeQueryProtocolPolicyPageByCriteria(HttpSession session, Integer pageIndex,Integer size,
			GatewayPolicy policy,String privilegeBranch,String bbrName,
			String polBeginDateBegin,String polBeginDateEnd) throws Exception{
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		
		Page page = new Page();
		Map<String,Object> map = new HashMap<String, Object>();
		if(pageIndex != -1){
			page.setCurrent(pageIndex);
			map = SqlUtil.buildPageMap(page);
		}
		
		page.setSize(size);
		//机构验证
		if(StrUtil.isEmpty(privilegeBranch)){
			throw new AppException("系统异常：机构不能为空");
		}else{
			if(!(channelInfoConfigService.checkIsHasPrivilege(session, privilegeBranch))){
				throw new AppException("用户权限不足");
			}	
		}
		map.put("privilegeBranch",privilegeBranch);
		
		map.put("dptCode", policy.getDptCde());
	
		
		
		//保单生效日期
		if(StrUtil.isNotEmpty(polBeginDateBegin)){
			polBeginDateBegin = polBeginDateBegin + " 00:00:00";
		}
		if(StrUtil.isNotEmpty(polBeginDateEnd)){
			polBeginDateEnd = polBeginDateEnd + " 23:59:59";
		}
		
		map.put("polBeginDateBegin", polBeginDateBegin);
		map.put("polBeginDateEnd", polBeginDateEnd);
		
		
		//合作伙伴代码
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(privilegeBranch);
		List<Map> channelInfoList = protocolPolicyListService.queryChannelListOfProtocol(channelInfo,"nocar");
		if(null == channelInfoList || channelInfoList.size() == 0){
			page.setResult("noChannelInfo");
			return page;
		}
		
		String channelCodeStr;
		if(StrUtil.isEmpty(policy.getPartnerNo())){
			channelCodeStr = "";
//			channelCodeStr = transList2InStr(channelCodeList);
		}else{
			List<String> channelCodeList = new ArrayList<String>();
			for (Map m : channelInfoList) {
				channelCodeList.add(m.get("CHANNELCODE").toString());
			}
			if(!channelCodeList.contains(policy.getPartnerNo())){
				page.setResult("error");
				page.setMessage("合作伙伴["+policy.getPartnerNo()+"]没有权限执行此操作");
				return page;
			}
			channelCodeStr="'"+policy.getPartnerNo()+"'";
		}	
		map.put("channelCodeStr", channelCodeStr);
		map.put("isHq", 'N');
		//合作伙伴子机构
//		if(StrUtil.isNotEmpty(policy.getPartnerSubCode()) && StrUtil.isEmpty(policy.getPartnerNo())){
//			page.setResult("error");
//			page.setMessage("合作伙伴子机构不为空，合作伙伴不允许为空");
//			return page;
//		}else if("00".equals(privilegeBranch)){
//			map.put("isHq", 'Y');
//		}
//		map.put("partnerSubCode", policy.getPartnerSubCode());
		
		map.put("bbrName", bbrName);
		map.put("polno", policy.getPolno());
		map.put("stateId", policy.getStateId());
		map.put("tradProdType", policy.getTradProdType());
		
		page.setType(map);
		return page;
	}
	//电子保单下载
	@RequestMapping(value = "/downloadProtocolPolicyFileByCriteria")
	public void downloadProtocolPolicyFileByCriteria(HttpSession session,HttpServletResponse response, 
			 Integer pageIndex,Integer size,GatewayPolicy policy,String privilegeBranch,String bbrName,
			String polBeginDateBegin,String polBeginDateEnd) throws Exception {
	
	Page page = beforeQueryProtocolPolicyPageByCriteria(session,-1,size, policy, privilegeBranch,bbrName, polBeginDateBegin, polBeginDateEnd);
	
	Map<String,Object> map = (Map<String, Object>) page.getType();
	List<Map<String, Object>> protocolPolicyList = protocolPolicyListService.queryProtocolPolicyListByCriteria(map);
	protocolPolicyListService.downloadProtocolPolicyFile(protocolPolicyList, response);
    }
	//点击编辑时根据保单号查询保单信息
	@RequestMapping(value = "/queryProtocolById")
	public @ResponseBody String queryProtocolById(HttpSession session,String polno) throws Exception{
		System.out.println(polno);
		Map<String,Object> map=protocolPolicyListService.queryProtocolById(polno);
		String jsonStr = JsonUtils.toJson(map);
		return jsonStr;
	}
	//编辑保单 
	@RequestMapping(value = "/saveUpProtocol")
	public @ResponseBody Result saveUpProtocol(HttpSession session,String polno,String rcv_prem_status,String rcv_prem_date) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("polno", polno);
		map.put("rcv_prem_status", rcv_prem_status);
		map.put("rcv_prem_date", rcv_prem_date);
		try{
			protocolPolicyListService.saveUpProtocol(map);
			return Result.success("修改成功");
		}catch(Exception e){
			return Result.error("修改失败");
		}
	}
	//批量更新模板下载 
	@RequestMapping(value = "/teamBBRDownLoad")
	public  void teamBBRDownLoad(HttpSession session,HttpServletResponse response) throws Exception{
		
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		String projectRoot = path.substring(0, path.indexOf("/WEB-INF"));
		
		StringBuilder root = new StringBuilder(projectRoot);
		
		  if (!root.toString().endsWith(java.io.File.separator)) {
		        root = root.append(java.io.File.separator);
		  }
		  
		  root = root.append("protocolTemplateFile.xls");
		 
		 String dir = root.toString();
		 logger.info("更新导入文件模板位置："+dir);
		 
		 File myFile=null;
		 ServletOutputStream outPutStream=null;
		 InputStream inputStream=null;
		 try{
			 myFile=new File(dir); 
			 if(myFile.exists()){
				 String fileName=java.net.URLEncoder.encode("protocolTemplateFile.xls","UTF-8");  
				 response.setHeader("Content-disposition","attachment; filename="+ fileName);  
				 response.setContentType("application/x-download"); 
		         outPutStream=response.getOutputStream();  
		         inputStream=new  BufferedInputStream(new FileInputStream(myFile));  
		         byte[] bytes=new byte[10240];
		         int len = 0;
		         while((len = inputStream.read(bytes)) != -1)  
		         {    
		             outPutStream.write(bytes,0,len);   
		         } 
		         outPutStream.flush();
			  }
		    }catch(IOException e){
		    	logger.info("更新导入模板文件不存在",e);
		  }finally{
			  if(inputStream!=null){
				  inputStream.close();
			  }
			  if(outPutStream!=null){
				  outPutStream.close();
			  }
		  }
		
	}
	
	//批量更新
	@RequestMapping(value = "/protocolReconciliation")
	public void addUserAgentInfo(@RequestParam MultipartFile reconciliationFile,HttpServletResponse response, HttpSession session) throws Exception {
		InputStream input = null;
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		Page<String>  page = new Page<String>();
		// 上传文件的原名(即上传前的文件名字)
		try {
				out = response.getWriter();
				input = reconciliationFile.getInputStream();
				GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
				ImportExcelEntity entity= new ImportExcelEntity();
				entity.setColumnName("polno,rcv_prem_status,rcv_prem_date");
				entity.setColumnValidateRule("1,1,6");
				entity.setExtraValidateRule("20_0_,21_200_");
				List<Map<String,Object>> lists= importExcelBuilderTool.parseExcel(input, entity);
				
				if(lists.size()>0){
					//用于从数据库 根据保单号查询
					String polnos="";
					//用于验证保单号
					String pols="";
					String statusErrorMsg = "";
					for(Map<String,Object> li:lists){
						polnos += ",'" + li.get("polno")+"'";
						//用于验证保单号
						pols+=li.get("polno")+",";
						//用于验证保单状态
						String rcv_prem_status= (String) li.get("rcv_prem_status");
						//用于验证收款日期
						String rcv_prem_date=(String) li.get("rcv_prem_date");
						if(!"0".equals(rcv_prem_status) && !"1".equals(rcv_prem_status)){
							statusErrorMsg+="保单号"+li.get("polno")+"状态不正确<br/>";
						}
						if("0".equals(rcv_prem_status) && null!=rcv_prem_date){
							statusErrorMsg+="保单号"+li.get("polno")+"状态为0时，收款日期应为空<br/>";
						} 
						if("1".equals(rcv_prem_status) && null==rcv_prem_date){
							statusErrorMsg+="保单号"+li.get("polno")+"状态为1时，请填写收款日期<br/>";
						}
					
					 }
					
					 if(StrUtil.isNotEmpty(statusErrorMsg)) throw new AppException(statusErrorMsg);
					 polnos = polnos.substring(1);
					 List<String> backLists = protocolPolicyListService.queryPolno(polnos);
					 if(backLists.size()==lists.size()){
						//批量更新文件
						 Map<String,Integer> result=protocolPolicyListService.batchUpdate(lists);
						page.setResult("success");
						page.setMessage("批量更新excel文件成功"+result.get("success")+"笔，"+"失败"+result.get("error")+"笔");
					  }else{
						  	//抛出保单号不存在异常
							String[] pols1=pols.split(",");
							List<String> list2 = new ArrayList<String>();
							for(String lis:pols1){
								if( !backLists.contains(lis) ){
									list2.add(lis);
							    }
						     }
							String nopolno="";
							for(String lis2:list2){
								nopolno += ","+lis2;
							}
							nopolno = nopolno.substring(1);
							page.setResult("error");
							page.setMessage("保单号 "+nopolno+"不存在，请检查修改");
					}
					
				}else{
					//抛出异常 excel为空
					page.setResult("error");
					page.setMessage("更新内容为空，请填入更新内容");
				}
					
		} catch (AppException a) {
			logger.info("---------Excel导入失败");
			page.setResult("error");
			page.setMessage(a.getMessage());
		}catch (Exception e) {
			logger.info("---------Excel导入失败");
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
}